package cn.song.convert;

import cn.song.domain.OrderDetail;
import cn.song.dto.OrderDto;
import cn.song.enums.ResultEnum;
import cn.song.exceptions.SellException;
import cn.song.form.OrderForm;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderForm2OrderDto {
    public static OrderDto convert(OrderForm orderForm){
        Gson gson = new Gson();
        OrderDto orderDto = new OrderDto();

        orderDto.setBuyerName(orderForm.getName());
        orderDto.setBuyerPhone(orderForm.getPhone());
        orderDto.setBuyerAddress(orderForm.getAddress());
        orderDto.setBuyerOpenid(orderForm.getOpenid());

       List<OrderDetail> orderDetails = new ArrayList<>();
       try{
           orderDetails =gson.fromJson(orderForm.getItems(),new TypeToken<List<OrderDetail>>(){}.getType());
       }catch (Exception e){
           log.error("对象转换错误 .StrIng is{}.", orderForm.getItems());
           throw  new SellException(ResultEnum.CONVERT_PARAMS_ERRRO);
       }
        orderDto.setOrderDetails(orderDetails);
       return  orderDto;


    }
}
